<template>
  <div class="w-full" :style="{ height: height + 'px' }">
    <div v-if="isEdit">
      <el-space>
        <div class="min-w-[190px]">
          <el-autocomplete v-model="search" :fetch-suggestions="querySearchAsync" value-key="name" placeholder="搜索标点"
            @select="onchange" />
        </div>
        <template v-if="showCreatePoly">
          <el-button @click="createPolygon" :disabled="createArea">
            添加区域
          </el-button>
          <el-button v-if="createArea" @click="stopCreatePolygon">
            停止添加
          </el-button>
        </template>
        <el-popover placement="bottom-start" :width="280">
          <template #default>
            <div class="demo-rich-conent flex flex-col gap-[10px]">
              <p>1.在输入框输入具体地址名称进行标点,标点后使用鼠标可移动标记点改变选择</p>
              <p>2.在地图上右键可选择标点</p>
              <p v-if="showCreatePoly">3.点击添加区域进行区域划定,新建区域后点击鼠标右键完成新增区域</p>
              <p v-if="showCreatePoly">4.在已划定区域空白圆圈上单击鼠标左键删除点位,拖动圆圈可修改区域</p>
              <p v-if="showCreatePoly">5.双击已选定地图区域可进行切换编辑区域</p>
            </div>
          </template>
          <template #reference>
            <el-icon color="#409eff">
              <QuestionFilled :size="60" />
            </el-icon>
          </template>
        </el-popover>
        <!-- <el-image :src="image"></el-image> -->
        <text>注：鼠标移动到地图点击右键开始标记点位</text>
       
      </el-space>
    </div>
    <div class="mt-[10px]" v-if="mt==true"></div>
    <div class=""  :style="{ height: isEdit ? `calc(${height}px - 42px)` : height + 'px' }">
      <el-amap class="h-full" ref="amapRef" :show-label="true" :center="centerValue" :zoom="zoom"
        :doubleClickZoom="false" @init="init">
       
        <!-- <el-amap-layer-image  
        v-if="image"
        :url="image" 
        :bounds="bounds" 
        :opacity="1" 
        :zIndex="100"
      /> -->
        <el-amap-mouse-tool v-if="createType" :type="createType" :showTooltip="true" :tooltip-text-map="tooltipOption"
          :textOptions="textOptions" :auto-clear="true" @draw="draw" />

        <template v-for="(polygon, index) in polygons">
          <el-amap-polygon v-model:path="polygon.path" :visible="polygon.visible" :editable="polygon.edit"
            :draggable="polygon.draggable" :strokeOpacity="polygon.strokeOpacity" :fillColor="polygon.fillColor"
            :strokeColor="polygon.strokeColor" :strokeWeight="polygon.strokeWeight" :fillOpacity="polygon.fillOpacity"
            :strokeDasharray="polygon.strokeDasharray" @adjust="addnode" @addnode="addnode" @removenode="addnode"
            @mouseover="mouseOver(index)" @mouseout="mouseOut(index)" @dblclick="dblclick(index)" />
        </template>

        <el-amap-marker v-for="(marker, index) in markers" :key="index" :position="marker.position" :draggable="true"
          :icon="amapIcon.redMarker" anchor="bottom-center" @dragend="dragends" :offset="{x: 0, y: 15}" />

        <!--      地图标点不可更改-->
        <el-amap-layer-labels v-if="fixedLabelMarkers.length > 0">
          <el-amap-label-marker v-for="(item, index) in fixedLabelMarkers" :key="index" :position="[item.lng, item.lat]"
            :icon="labelOptions.blueMarker.icon" />
        </el-amap-layer-labels>
       
      </el-amap>
    </div>
  </div>
</template>

<script setup lang="ts"> 
import { ref, watch } from "vue";
import { cloneDeep, isArray } from "@pureadmin/utils";
import { QuestionFilled } from "@element-plus/icons-vue";
import {
  ElAmap,
  ElAmapMarker,
  ElAmapMouseTool,
  ElAmapPolygon,
  ElAmapLabelMarker,
  ElAmapLayerLabels,
  ElAmapLayerImage
} from "@vuemap/vue-amap";
import { useDark } from "@/views/welcome/utils";
import { useMap } from "./useMap"
import { contextMenuOptions, markersOption } from "@/components/mapForm/types";
import { getConfig } from "@/config";
import { PLATFORM_Map, usePageVariablesStoreHook } from '@/store/modules/pageVariables'
const emits = defineEmits(['update:center', 'update:area'])


const props = defineProps({  //父子组件参数传递
  /*地图中心标点，可编辑*/
  center: {
    type: [Array, Boolean],
    default: () => []
  },
  area: {
    type: Array,
    default: () => []
  },
  zoom: {
    default: 12
  },
  isEdit: {
    type: Boolean
  },
  /*地图高度*/
  height: {
    type: Number,
    default: 600
  },
  mt: {
    type: Boolean,
    default:true
  },
  /**
   * 是否显示区域绘制
   */
  showCreatePoly: {
    type: Boolean,
    default: false
  },
  // 地图默认标点 不可编辑
  labelMarkers: {
    type: Array<markersOption>,
    default: () => []
  },
  image: {
    type: String,
    default: ""
  },
  bounds: {
    type: Array, //[104.044794 ,30.644344,104.050713, 30.648466]
    default: () => []
  },
})

const { tooltipOption, textOptions, theme, polyOption, polyFillColor, amapIcon, registerContextMenus, labelOptions, setDraw } = useMap()
const { isDark } = useDark();
const createArea = ref(false) // 点击开始、停止添加区域
const search = ref("") //搜索
const createType = ref("") //鼠标工具的类型
const polygons = ref([])  //区域数组
const paths = ref([])
const zoom = ref(15);
const centerValue = ref([]); // 初始中心点
const markers = ref([]) //标记点
const fixedLabelMarkers = shallowRef<markersOption[]>([])
//  console.log("地图",props);

let map = null;
onBeforeUnmount(() => {
  if (map) {
    map.destroy()
    map = null
  }
})
const  cen = usePageVariablesStoreHook().getPlatform()
watch(() =>cen, (newVal) => {
  // 
  
  if(cen == PLATFORM_Map.operate){
    centerValue.value =  [usePageVariablesStoreHook().operateProjectInfo.lng,usePageVariablesStoreHook().operateProjectInfo.lat]
  }else{
    centerValue.value =  [104.037015,30.712302]
  }
},{immediate: true})
watch(() => isDark.value, (newVal) => {
  if (map) {
    map.setMapStyle(isDark.value ? theme.darkblue : theme.normal)
  }
})

onMounted(() => {
  fixedLabelMarkers.value = props.labelMarkers
})
// console.log('theme',theme);

const init = (e) => {  //初始化
  map = e;
  map.setMapStyle(isDark.value ? theme.darkblue : theme.normal)
  // map.setMapStyle(isDark.value ? darkblue : normal)

  //注册右键菜单
  if (props.isEdit) {
    registerContextMenus(map, <contextMenuOptions>{
      addMarker: (position) => {
        addMarker(position.lng, position.lat)
      }
    })
  }

  // 地图初始化完成执行
  map.on('complete', () => {
    nextTick(() => {
      initCenter()
      initPolygon()
      setTimeout(() => {
        map.setFitView();
      }, 1000);
    })
  });

}

/*初始化中心点*/
async function initCenter() {
  const val = props.center
  if (val && isArray(val) && val.length === 2 && val[0] && val[1]) {
    centerValue.value = val
    addMarker(val[0], val[1])
  }
}

/*初始化路径*/
async function initPolygon() {
  const val = props.area
  if (val && isArray(val)) {
    polygons.value = [] //置空区域数组
    paths.value = []
    if (JSON.stringify(val).slice(0, 3) !== "[[[") { //如果传过来的不是[[[就不继续执行
      return;
    } else {
      val.forEach(item => { //遍历区域数组
        let i = cloneDeep(polyOption)
        i.path = item
        polygons.value.push(i)
        paths.value.push(item)
      })
    }
  }
}

function draw(e) { //有2个参数data,targer 第一个参数为绘制生成的对应数据，第二个为绘制的图形对象
  let i = cloneDeep(polyOption)
  i.path = e
  polygons.value.push(i)
  paths.value.push(e)
  emits("update:area", paths.value)
}

const addnode = (e) => {   // 鼠标操作折线图 调整 增加 删除
  setTimeout(() => {
    paths.value = polygons.value.map(item => {
      return item.path
    })
    // console.log(paths.value);
    emits("update:area", paths.value)
  }, 500)
}

function mouseOver(e) { // 鼠标经过
  polygons.value[e].fillColor = polyFillColor.hoverFillColor;
}

function mouseOut(index) { //鼠标移出
  polygons.value[index].fillColor = polyFillColor.fillColor;
}

function dblclick(index) { //鼠标左键双击事件
  if (props.isEdit) {
    polygons.value[index].edit = !polygons.value[index].edit;
    // call();
  }
}

//点标记拖拽移动结束触发事件
const dragends = e => {
  centerValue.value = [e.lnglat.lng, e.lnglat.lat];
  emits("update:center", centerValue.value);
};

const addMarker = (lon, lat) => {  //标记点
  let position = {
    position: [lon, lat]
    
  }
  markers.value = [position]
  emits("update:center", position.position)
}

/*地址搜索*/
const onchange = (value) => { //选择地址
  search.value = value.name
  toMap(value)
}

// setTimeout(() => {
//   console.log("地图接收到数据", props);
//             }, 500)

const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  autoInput(queryString, cb)
}

// 获取搜索信息
function autoInput(query, cb) {
  map.plugin('AMap.AutoComplete', function () {
    var autoOptions = {}
    var placeSearch = new AMap.AutoComplete(autoOptions);
    placeSearch.search(query, function (status, result) {
      // 搜索成功时，result即是对应的匹配数据
      // console.log("获取搜索信息",result);
      let place = [];
      if (result === "NO_PARAMS" || status === "error" || status === "no_data") return
      if (result.info.toLowerCase() === "ok" && result.tips.length > 0) {
        result.tips.forEach(item => {
          // console.log(item);
          if (item.location) {
            place.push(item);
            setTimeout(() => {
              cb(place)
            }, 500)
          }
        })

      }
    })
  })
}

function createPolygon() { //开始停止添加区域
  createArea.value = !createArea.value
  setDraw(createArea.value)
  if (createArea.value) {
    createType.value = "polygon"
  } else {
    createType.value = ""
  }
}

function stopCreatePolygon() {
  setDraw(false)
  createArea.value = false
  createType.value = ""
}

const toMap = (item) => {  //进行标点
  addMarker(item.location.lng, item.location.lat)
  centerValue.value = [item.location.lng, item.location.lat]
}

/*设置地图标点*/
const setLabelMarkers = async (markers?: markersOption[]) => {
  if (isArray(markers)) {

    fixedLabelMarkers.value = markers
  }
}

const setCenter = (center) => {
  map.setCenter(center)
}

defineExpose({
  setLabelMarkers,
  setCenter
})
</script>
